import functools

import logging 
# 定义日志记录器及等级、日志处理路径及板式
logger = logging.getLogger('F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict/plt_bar.py')

setFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

addHandler = logging.FileHandler('F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict/plt_bar.py.log')
addHandler.setFormatter(setFormatter)

logger.addHandler(addHandler)







logger.setLevel(logging.INFO)
logger.info('Start print log[F:\AI_BASIC\ai_-basic\AI_Basic_lab\RegrassionAndPredict\6plt_bar.py]')

import pandas as pd
# 二手房数据
house_price_df = pd.read_csv('F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict/bj_house_information.csv')


#册除一些不重要的列
to_drop = ['Id', '朝向', '电梯', '装修', '楼层', '小区名称', '地点', '楼龄']
house_price_df_clean = house_price_df.drop(to_drop, axis=1)
# 显示列名
print(house_price_df_clean.columns)
print(house_price_df_clean.head())


# 重新摆放列位置
columns = ['房屋总价', '建筑面积', '区域','户型']
house_price_df_clean = pd.DataFrame(house_price_df_clean, columns = columns)
print(house_price_df_clean.head())

house_total_num = house_price_df_clean['建筑面积'].count()
print('房价数据集总数量为: ' + str(house_total_num))

#数据清洗
df = house_price_df_clean
df['房屋单价'] = df['房屋总价']/df['建筑面积']
# 对汇总数据再次清洗
df.dropna(how='any')
df.drop_duplicates(keep='first', inplace=True)
# 一些别墅的房屋单价有异常，删选价格少于25万一平的
df = df.loc[df['房屋单价']<25]


#####################################################################################
# 对二手房区域分组对比二手房数量和每平米房价
df_house_count = df.groupby('区域')['房屋总价'].count().sort_values(ascending=False)
df_house_mean = df.groupby('区域')['房屋单价'].mean().sort_values(ascending=False)

# 设置X轴刻度标签：
def auto_xtricks(rects, xticks):
    x = []
    for rect in rects:
        x.append(rect.get_x() + rect.get_width() / 2)
    x = tuple(x)
    plt.xticks(x, xticks)

# 设置数据标签：
def auto_tag(rects, data=None, offset=[0, 0], size=14):
    for rect in rects:
        try:
            height = rect.get_height()
            plt.text(rect.get_x() + rect.get_width() / 2.4, 1.01 * height, '%s' % int(height), fontsize=size)
        except AttributeError:
            x = range(len(data))
            y = data.values
            for i in range(len(x)):
                plt.text(x[i] + offset[0], y[i] + 0.05 + offset[1], y[i], fontsize='14')

def auto_tag_float(rects, data=None, offset=[0, 0], size=14):
    for rect in rects:
        try:
            height = rect.get_height()
            plt.text(rect.get_x() + rect.get_width() / 2.4, 1.01 * height, '%s' % round(float(height), 1),
                     fontsize=size)
        except AttributeError:
            x = range(len(data))
            y = data.values
            for i in range(len(x)):
                plt.text(x[i] + offset[0], y[i] + 0.05 + offset[1], y[i], fontsize='14')

import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(20, 10))
plt.rc('font', family='SimHei', size=13)
plt.style.use('ggplot')

# 各区域二手房数量对比
plt.subplot(212)
plt.title(u'各区域二手房数量对比', fontsize=20)
plt.ylabel(u'二手房总数量（单位：间）', fontsize=15)
rect1 = plt.bar(np.arange(len(df_house_count.index)), df_house_count.values, color='c')
auto_xtricks(rect1, df_house_count.index)
auto_tag(rect1, offset=[-1, 0])

# 各区域二手房平均价格对比
plt.subplot(211)
plt.title(u'各区域二手房平均价格对比', fontsize=20)
plt.ylabel(u'二手房平均价格（单位：万/平米）', fontsize=15)
rect2 = plt.bar(np.arange(len(df_house_mean.index)), df_house_mean.values, color='c')
auto_xtricks(rect2, df_house_mean.index)
auto_tag_float(rect2, offset=[-1, 0])

plt.show()

logger.info('End print log[F:\AI_BASIC\ai_-basic\AI_Basic_lab\RegrassionAndPredict\6plt_bar.py]')
logger.info('..')